package Hot_100;

import java.util.Scanner;

//相交链表
public class Hot_100_160 {
    /**
     * 值域
     */
    public static class ListNode {
        int val;
        ListNode next;

        public ListNode(int x) {
            val = x;
            next = null;
        }
    }

    /**
     * 主函数
     *
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        ListNode l1 = new ListNode(-1);
        ListNode l2 = new ListNode(-1);
        System.out.print("请输入l1链表节点个数: ");
        int m = sc.nextInt();
        System.out.print("输入l1节点值: ");
        l1 = Create(m);
        System.out.print("结果: ");
        Print(l1);
        System.out.println();
        System.out.print("请输入l2链表节点个数: ");
        int n = sc.nextInt();
        System.out.print("输入l2节点值: ");
        l2 = Create(n);
        System.out.print("结果: ");
        Print(l2);
        System.out.println();
        System.out.print("相交节点: ");
        l1 = getIntersectionNode(l1, l2);
        System.out.print(l1.val);
    }

    /**
     * 创建链表函数
     *
     * @param n
     * @return
     */
    public static ListNode Create(int n) {
        Scanner sc = new Scanner(System.in);
        //定义投节点
        ListNode head = new ListNode(-1);
        ListNode p = head, q = head;
        //给头节点赋值
        p.val = sc.nextInt();
        n--;
        //依次赋值，形成链
        while (n > 0) {
            q = p;
            p = new ListNode(-1);
            p.val = sc.nextInt();
            q.next = p;
            n--;
        }
        return head;
    }

    /**
     * 相交节点
     * @param headA
     * @param headB
     * @return
     */
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode A = headA, B = headB;
        while (A != B) {
            if (A != null) {
                A = A.next;
            } else {
                A = headB;
            }
            if (B != null) {
                B = B.next;
            } else {
                B = headA;
            }
        }
        return A;
    }

    /**
     * 输出链表元素函数
     *
     * @param head
     */
    public static void Print(ListNode head) {
        for (ListNode p = head; p != null; p = p.next) {
            System.out.print(p.val + " ");
        }
    }
}
//时间复杂度: O(m+n)
//空间复杂度: O(1)